/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.business;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.BusinessConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.dao.business.BusinessDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.orf.Order;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import net.dgg.dggcloud.service.jrcrm.service.orf.OrderService;
import net.dgg.dggcloud.service.jrcrm.utils.BizExceptionUtil;
import net.dgg.dggcloud.service.service.user.UserService;

/**
 * @ClassName 〈BusinessAbilityService>
 * @Description 商机模块提供外部接口的service
 * @Author 朱永波
 * @Date 2017/11/3 11:49
 */
@Service
public class BusinessAbilityService extends BaseService {
	@Autowired
	private BusinessDao businessDao;
	@Resource
	private CustomerRecordService customerRecordService;
	@Resource
	private BusinessService businessService;

	@Resource
	private OrderService orderService;
	@Resource
	private MessageService messageService;
	@Resource
	private BusinessDxService businessDxService;
	@Resource
	private UserService userService;

	@Resource
	private CustomerService customerService;

	/**
	 * 外部接口，查询客户的相关商机
	 *
	 * @param customerId 客户编号
	 * @retur 返回map对象的list集合
	 */
	public List<Map> getCustomerBusinessList(Long customerId) {
		BizExceptionUtil.isException(null == customerId, "客户id不能为空");
		Map map = new HashMap();
		map.put("customerId", customerId);
		map.put("notInBusinessLocation",BusinessConstant.BUS_STORE_FQ+"");
		return businessDao.listBusinessByMap(map);
	}

	/**
	 * 外部接口，根据id查询商机详情
	 *
	 * @param busId 商机编号
	 * @return Business 返回商机实体
	 */
	public Business getBusinessById(Long busId) {
		return repository.get(Business.class, busId);
	}

	/**
	 * 外部接口，用于订单更新商机状态
	 *
	 * @param
	 * @param userId  操作用户id
	 * @param operate 操作,仅可以为签单(BUS_4)、成单(BUS_5)、退单(BUS_6)、签单审核驳回(BUS_4_1)
	 */
	public void updateBusinessOrderInfo(Order order, Long userId, String operate) {

		BizExceptionUtil.isException(null == order, "商机id不能为空");
		Long businessId = order.getBusinessId();
		BizExceptionUtil.isException(null == businessId, "商机id不能为空");
		BizExceptionUtil.isException(null == userId, "操作人id不能为空");
		BizExceptionUtil.isException(StringUtils.isBlank(operate), "操作类型不能为空");

		if (!operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER) && !operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS)
				&& !operate.equals(CustomerRecordConstant.BUS_OPERATE_BACKORDER) && !operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER_BACK)) {
			throw new BizException("操作类型不存在", 10001);
		}
		Business business = getBusinessById(businessId);
		BizExceptionUtil.isException(null == business, "商机不存在");

		User user = repository.get(User.class, userId);
		BizExceptionUtil.isException(null == user, "操作人不存在");

		String curStatus = business.getBusinessStatus();// 商机当前状态
		if (operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER)) {// 签单
			BizExceptionUtil.isException(business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EMP.intValue()
					&& business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EP, "商机不在个人库，不可操作");
			BizExceptionUtil.isException(business.getFollowerId().longValue() != userId.longValue(), "只能对自己的商机进行签单");
//            BizExceptionUtil.isException(!curStatus.equals(BusinessConstant.BUS_STATUS_FOLLOWING) && !curStatus.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW), "只能对待跟进和跟进中的商机进行签单");//只能对跟进中和待跟进的商机签单
			// 已签单的商机如果没有订单，可以再次下单 2018年1月3日 14:25:13
			// TODO 事务问题，订单已经保存了才调的这个方法，所以已签单的始终会查到一个商机，去掉验证
			/*
			 * if (curStatus.equals(BusinessConstant.BUS_STATUS_SIGNED)) { Map businessMap =
			 * new HashMap(); businessMap.put("businessId", businessId); List<Map> orderMaps
			 * = orderService.queryOrderByBusinessByMap(businessMap); if (null != orderMaps
			 * && !orderMaps.isEmpty()) { for (Map orderMap : orderMaps) { if
			 * (Long.parseLong(orderMap.get("id") + "") != order.getId()) { throw new
			 * BizException("商机已签单，不能再次下单", 10001); } } if (orderMaps.size() > 1) { throw
			 * new BizException("商机已签单，不能再次下单", 10001); } } } else if
			 * (!curStatus.equals(BusinessConstant.BUS_STATUS_FOLLOWING) &&
			 * !curStatus.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) { throw new
			 * BizException("只能对待跟进和跟进中的商机进行签单", 10001); }
			 */

			business.setBusinessStatus(BusinessConstant.BUS_STATUS_SIGNED);
			business.setLastFollowRecordContent("签单");
			business.setOrderTime(new Date());
			business.setLastFollowTime(new Date());
			if (null != order) {
				business.setOrderId(order.getId());
				business.setOrderNo(order.getOrderNo());
			}
			business.setWillDropTime(null);
			// 给电销分配人员推送消息
			if (business.getDxAllotUserId() != null) {
				String[] msgs = { business.getNo(), user.getName(), user.getLoginName() };
				messageService.sendMessageReady(userService.getUserById(business.getDxAllotUserId()), user, msgs, "SJ_XD_TX");
			}

		}
		if (operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS)) {// 成单
			BizExceptionUtil.isException(!curStatus.equals(BusinessConstant.BUS_STATUS_SIGNED) && !curStatus.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED), "非签单商机不能成单");

			if (curStatus.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED)) {
				return;// 已成单商机再次成单不再做操作
			}
			business.setBusinessStatus(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED);
			business.setLastFollowRecordContent("成单");
			// 成单及退单代表商机完结
			business.setFinishTime(new Date());
			business.setLastFollowTime(new Date());
			businessService.setBusinessWillDropDate(business);
		}
		if (operate.equals(CustomerRecordConstant.BUS_OPERATE_BACKORDER)) {// 退单
			BizExceptionUtil.isException(!curStatus.equals(BusinessConstant.BUS_STATUS_SIGNED) && !curStatus.equals(BusinessConstant.BUS_STATUS_ORDER_BACK), "非签单商机不能退单");

			if (curStatus.equals(BusinessConstant.BUS_STATUS_ORDER_BACK)) {
				return;// 已退单商机再次退单不再做操作
			}
			business.setBusinessStatus(BusinessConstant.BUS_STATUS_ORDER_BACK);
			business.setLastFollowRecordContent("退单");
			// 成单及退单代表商机完结
			business.setFinishTime(new Date());
			businessService.setBusinessWillDropDate(business);
		}
		if (operate.equals(CustomerRecordConstant.BUS_OPERATE_ORDER_BACK)) {// 删除订单
			BizExceptionUtil.isException(!curStatus.equals(BusinessConstant.BUS_STATUS_SIGNED), "非签单商机不能删除订单");

			business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
			business.setLastFollowRecordContent("删除订单");
			business.setLastFollowTime(new Date());
			businessService.setBusinessWillDropDate(business);
		}

		business.setLastFollowRecordTime(new Date());
		business.setLastFollowRecordUser(user.getName() + user.getLoginName());
		business.setBusinessOperate(operate);
		business.setUpdaterUser(user);
		// 保存备注记录
		Map recordMap = new HashMap();
		recordMap.put("tableName", Business.TABLE_NAME);
		recordMap.put("tableId", business.getId());
		recordMap.put("cusId", business.getCustomerId());
		recordMap.put("recordType", operate);
		recordMap.put("content", business.getLastFollowRecordContent());
		recordMap.put("ext3", business.getNo());// 商机编号
		recordMap.put("toUserId", business.getFollowerId());// 新的跟进人，这里为方便定时器的转化率统计，把商机跟进人放进去
		recordMap.put("toUserOrgId", business.getFollowerOrganizationId());// 新的跟进人部门
		recordMap.put("ext1", business.getBusinessStage());// 商机当前阶段
		recordMap.put("ext2", business.getBusinessLocation());// 商机所在库
		recordMap.put("ext4", curStatus);// 商机当前状态
		recordMap.put("ext3", business.getNo());// 商机编号
		recordMap.put("operateUser", userId);
		customerRecordService.saveCustomerRecord(recordMap);

		repository.saveOrUpdate(business);
	}

	/**
	 * 查询当前跟进人vip数量
	 *
	 * @param map followerId ：跟进人id
	 * @return
	 */
	public int vipCountByFollowerId(Map map) {
		map.put("isVip", "1");// vip标示
		return businessDao.countBusinessByMap(map);
	}

	/**
	 * 通过客户id更新客户的所有商机上的客户属性字段
	 *
	 * @param customerAttrFlag 客户属性
	 * @param customerId       客户id
	 * @return
	 */
	public int updateCustomerBusinessAttr(String customerAttrFlag, Long customerId) {
		Map newInfo = new HashMap();
		newInfo.put("customerId", customerId);
		newInfo.put("customerAttrFlag", customerAttrFlag);
		return businessDao.updateCustomerBusinessAttr(newInfo);
	}

}
